package com.yunshipei.ui.view;

import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewConfiguration;

import com.yunshipei.core.utils.CommonUtils;
import com.yunshipei.utils.BaseUtil;

/**
 * Created by apple on 2017/7/6.
 */

public class SwipeLayout extends SwipeRefreshLayout {
    protected Context mContext;
    private boolean canRefresh;
    protected float startY;
    protected boolean isScrollTop = true;


    public SwipeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
    }

    public SwipeLayout(Context context) {
        super(context);
        this.mContext = context;
    }

    public void setCanRefresh(boolean canRefresh) {
        this.canRefresh = canRefresh;
    }

    public void isScrollTop(boolean canRefresh) {
        this.isScrollTop = canRefresh;
    }


    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        int dy = 0;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startY = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                float endY = event.getY();
                dy = (int) (startY - endY);//如果上滑动则认为不到顶端。到顶到js将isScrollTop置为true
                if (canRefresh) {
                    if (dy > 0 && dy > ViewConfiguration.get(mContext).getScaledTouchSlop()) {//大于最小滑动距离，认为不是点击
                        isScrollTop = false;
                    }
                    if (isScrollTop) {
                        setEnabled(true);
                    } else {
                        setEnabled(false);
                    }
                } else {
                    setEnabled(false);
                }
                break;
            case MotionEvent.ACTION_UP:
                setEnabled(true);
                if(dy > ViewConfiguration.get(mContext).getScaledTouchSlop()){//如果点击默认可以刷新
                    isScrollTop = false;
                }
                break;

        }
        return super.onInterceptTouchEvent(event);
    }
}
